import axiosService from './axiosService';
import * as vscode from 'vscode';
import { AxiosError } from 'axios';

export class BundleService {
    private authData = {
        username: 'admin',
        password: 'apusic$2021'
    };

    constructor() {
        const address = vscode.workspace.getConfiguration('server.address');
    }

    async login() {
        console.log('start logining to bundle cloud...');

        let res;

        try{
            res  = await axiosService.post('/user/login', this.authData);
        } catch(err) {
            const axiosError = err as AxiosError;
            if(err) {
                vscode.window.showInformationMessage('Bundle Cloud login Error: ' + axiosError.message);
                return false;
            }
        }

        if(res) {
            const token = res.headers['set-cookie'][0].split(';')[0];
            // set cookie header
            axiosService.defaults.headers['Cookie'] = token;

            return true;
        }
    }

    async fetchProjects() {
        console.log('start fetching projects...');
        return await axiosService.get('/project');
    }

    async fetchBundles(projectId: number) {
        console.log(`start fetching bundles of project ${projectId}...`);
        return await axiosService.get(`/bundle?projectId=${projectId}`);
    }
}